﻿using EMall.Application;
using EMall.Query;
using EMall.Uow;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

namespace EMall.IdentityService.Roles
{
    public class RoleAppService : ApplicationService, IRoleAppService
    {
        private readonly RoleManager<Role> _roleManager;
        public RoleAppService(RoleManager<Role> roleManager)
        {
            _roleManager = roleManager;
        }
        [UnitOfWork]
        public async Task CreateAsync(CreateRoleDto input)
        {
            var role = new Role(input.Name,input.Enabled);
            await _roleManager.CreateAsync(role);
        }
        [UnitOfWork]
        public async Task UpdateAsync(UpdateRoleDto input)
        {
            var role = await _roleManager.FindByIdAsync(input.Id.ToString());
            role.Update(input.Name,input.Enabled);
            await _roleManager.CreateAsync(role);
        }
        [UnitOfWork]
        public async Task DeleteAsync(DeleteRoleDto input)
        {
            var role = await _roleManager.FindByIdAsync(input.Id.ToString());
            await _roleManager.DeleteAsync(role);
        }
        public async Task<RoleDto> GetAsync(int id)
        {
            var role = await _roleManager.FindByIdAsync(id.ToString());
            return Mapper.Map<RoleDto>(role);
        }
        public async Task<IEnumerable<RoleListDto>> GetListAsync(GetRoleListQueryDto input)
        {
            var data = await _roleManager.Roles
               .Sorting(input.Sorting)
               .ToListAsync();
            return Mapper.Map<List<Role>, List<RoleListDto>>(data);
        }
        public async Task<IPagedList<RoleListDto>> GetPagedListAsync(GetRoleListPagingAndSortingQueryDto input)
        {
            var data = await _roleManager.Roles
               .Sorting(input.Sorting)
               .ToPagedListAsync(input.PageIndex, input.PageSize);
            return Mapper.Map<Role, RoleListDto>(data);
        }
    }
}